package com.hcj.util.commonUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 短信发送工具类
 * @author Henry
 */
public class SmsUtil {
	
	private static final String SMS_SIGN = "【互联网产业集群】";
	private static final String API_KEY = "d0569303c0db8403f4c77cb45bfade88";
	
	/**
	 * 短信类型：注册会员
	 */
	public static final String SEND_TYPE_REGISTER = "register";
	/**
	 * 短信类型：找回密码
	 */
	public static final String SEND_TYPE_FIND_PASSWORD = "findPassword";
	
	/**
	 * @param mobile
	 *            :手机
	 * @param content
	 *            :内容
	 * @return 返回结果
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("unchecked")
	public static boolean sendSms(String mobile, String content) throws UnsupportedEncodingException {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    content = SMS_SIGN + content;
	    String httpUrl = "http://apis.baidu.com/kingtto_media/106sms/106sms";
	    String httpArg = "mobile="+mobile+"&content="+URLEncoder.encode(content, "UTF-8");;
	    httpUrl = httpUrl + "?" + httpArg;
	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey",  API_KEY);
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	        Map<String, String> map = XMLUtilNew.doXMLParse(result);
	        if(map != null) {
	        	String status = map.get("returnstatus");
	        	if(status.toLowerCase().equals("success")) {
	        		return true;
	        	}
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return false;
	}
	
	public static void main(String[] args) throws Exception {
		SmsUtil.sendSms("14787895215", "12345");
	}
}
